import java.util.ArrayDeque;
import java.util.Deque;

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    Integer prevVal = null;
    int minimumDiff = Integer.MAX_VALUE;

    public int getMinimumDifference(TreeNode root) {
        dfs(root);
        return minimumDiff;
    }

    void dfs(TreeNode root) {
        if (root == null) {
            return;
        }

        dfs(root.left);
        if (prevVal != null) {
            minimumDiff = Math.min(minimumDiff, Math.abs(prevVal - root.val));
        }
        prevVal = root.val;
        dfs(root.right);
    }
}

//迭代
class Solution1 {
    public int getMinimumDifference(TreeNode root) {
        Deque<TreeNode> stack = new ArrayDeque<>();
        TreeNode cur = root;
        Integer prevVal = null;
        int minDiff = Integer.MAX_VALUE;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();

            if (prevVal != null) {
                minDiff = Math.min(minDiff, Math.abs(prevVal - cur.val));
            }
            prevVal = cur.val;

            cur = cur.right;
        }
        return minDiff;
    }
}